import { message as Message } from "antd";
import axios from "axios";
import { clearPersistor } from "../utils/common";
import { getToken } from "../utils/user-token";
import { store } from "../store";
import { logoutReducer } from "../store/userInfoReducer";
import router from "../router";

const instance = axios.create({
  timeout: 20 * 1000,
});

instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = `Bearer ${getToken()}`;
    return config;
  },
  (error) => Promise.reject(error)
);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
instance.interceptors.response.use((res: any = {}) => {
  const resData = (res.data || {}) as ResType;
  const { code, message, result = {} } = resData;
  if (code > 0) {
    if ([10101, 10102].includes(code)) {
      store.dispatch(logoutReducer());
      clearPersistor();
      router.navigate("/");
    }
    if (message) Message.error(message);
    throw new Error(message);
  } else {
    if (message) Message.success(message);
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return result as any;
});

export default instance;

export type ResType = {
  code: number;
  result?: ResDataType;
  message?: string;
};

export type ResDataType = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any;
};
